<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect, NFlex, useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
import { exportToExcel } from '@/utils/exportUtils'
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

defineOptions({ name: '退款订单记录' })
const instance = getCurrentInstance();
const nameFromInstance = instance?.type.name;

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const message = useMessage()

const handleExport = async () => {
  try {
    // 显示加载状态
    const loading = message.loading('正在准备导出数据...', { duration: 0 })

    // 获取表格数据
    const { data: tableData } = await api.getOrderList({
      ...queryItems.value,
      refund_status: 3,
      is_export:1,
    })

    if (!tableData || tableData.length === 0) {
      message.warning('没有数据可以导出')
      return
    }

    // 处理数据格式
    const exportData = tableData.map(item => ({
      单号: item.id,
      订单类型: item.order_type,
      客户姓名: item.user_name,
      实际支付: item.amount,
      下单时间: item.created_at,
      退款时间: item.refund_time,
      退款金额: item.refund_price,
      订单状态: item.refund_status === 3 ? '已退款' : '未退款'
    }))

    // 导出Excel
    exportToExcel(exportData, `退款订单记录_${formatDate(new Date())}`)
    message.success('导出成功')
    loading?.destroy()
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败: ' + error.message)
  } finally {
    loading?.destroy()
  }
}

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  goods_all:[],
  flag_data:[{id:1,name:"储值金"},{id:0,name:"普通"}],
  is_check_data:[{id:1,name:"已通过"},{id:0,name:"待审核"}],
  select_customers:[],
  search_loading:false,
  show_detail:false,
  show_data:[],
  detail:[],
  show_refund:false,
  refundForm:{
    refund_price:0,
    refund_remark:"",
    refund_time:new Date().toISOString().split('T')[0]
  }
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '退款订单记录',
  initForm: {},
  doCreate: api.createCouponUse,
  doUpdate: api.updateCouponUse,
  doDelete: api.deleteCouponUse,
  refresh: () => $table.value?.handlerefresh(),
})


onMounted(() => {
  queryItems.value.refund_status = 3
  $table.value?.handleSearch()
})

function on_check(item,status){
  if(status===1){
    api.on_check({
      id:item.id,
    }).then((res) => {
      message.success('审核通过');
      $table.value?.handleSearch()
    })
  }else{
    api.on_cancel({
      id:item.id,
    }).then((res) => {
      message.success('作废成功')
      $table.value?.handleSearch()
    })
  }
}

function on_detail(item){

    api.detailOrder({
      id:item.id,
    }).then((res) => {
      data.show_detail = true
      data.show_data = item
      data.detail = res.data
    })
}

function detail_button(type){
    if(type===1){
      on_check(data.show_data,1)
    }
    if(type===2){
      on_check(data.show_data,2)
    }
    if(type===3){
      data.show_refund = true
      data.refundForm.id = data.show_data.id
    }
}
function save_refund(){
      if(data.refundForm.refund_price<=0){
        message.error('请输入退款金额')
        return
      }
      api.on_refund(data.refundForm).then((res) => {
        message.success('退款成功')
        data.show_refund = false
        data.show_detail = false
        $table.value?.handleSearch()
      })
}

const columns = [
  {
    title: '单号',
    key: 'id',
    width: 50,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '订单类型',
    key: 'order_type',
    width:100,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      let type = "primary"
      if(row.flag===1){
        type = 'error'
      }
      return h(NTag, { type: type,size:"medium",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.order_type })
    },
  },
    {
    title: '客户姓名',
    key: 'user_name',
    width: 80,
    align: 'left',
    render(row) {
      return h(NFlex, {},
        [h(NButton, {
          size: "small",
          dashed: true,
          type: "primary",
        }, {
          default: () => (row.user_name)
        })]
      )

    },
  },
    {
    title: '实际支付',
    key: 'amount',
    width:100,
    align: 'center',
    ellipsis: { tooltip: true },
  },
{
    title: '下单时间',
    key: 'created_at',
    width:120,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '退款时间',
    key: 'refund_time',

    width:120,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '退款金额',
    key: 'refund_price',
    width:100,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '订单状态',
    key: 'refund_status',
    width:60,
    align: 'center',
    render(row) {
      if(row.refund_status === 3){
        return h(NTag, { type: 'error',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => '已退款' })
      }else{
        return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => "未退款" })
      }

    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 60,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [

        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-left: 8px;',
              onClick: () => {
                on_detail(row)
              },
            },
            {
              default: () => '详情',
            }
          ),
          []
        ),
      ]
    },
  },
]

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}



</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer title="退款订单列表">
        <template #action>
          <NButton type="info" @click="handleExport">
            <TheIcon icon="material-symbols:download" :size="18" class="mr-5" />导出Excel
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getOrderList"
          :scroll-x="1200"
          :maxheight="420"
        >
          <template #queryBar>
            <QueryBarItem label="订单编号" :label-width="80">
              <NInput
                v-model:value="queryItems.id"
                clearable
                type="text"
                placeholder="订单编号"
                style="width: 200px;"
              />
            </QueryBarItem>
            <QueryBarItem label="客户姓名" :label-width="80">
              <NInput
                v-model:value="queryItems.name"
                clearable
                type="text"
                placeholder="客户姓名/病历号/手机号"
                style="width: 200px;"
              />
            </QueryBarItem>
            <QueryBarItem label="付款时间" :label-width="70">
              <NDatePicker
                  v-model:value="datetimeRange"
                  type="datetimerange"
                  clearable
                  placeholder="请选择时间范围"
                  @update:value="handleDateRangeChange"
              />
            </QueryBarItem>


            <QueryBarItem label="订单类型" :label-width="80">
              <NSelect
                v-model:value="queryItems.flag"
                style="width: 200px;"
                :options="data.flag_data"
                clearable
                label-field="name"
                value-field="id"
                placeholder="选择订单类型"
              />
            </QueryBarItem>


            <QueryBarItem label="创建人" :label-width="80">
              <NInput
                v-model:value="queryItems.created_uname"
                clearable
                type="text"
                placeholder="输入创建人姓名"
                style="width: 200px;"
              />
            </QueryBarItem>

            <QueryBarItem label="审核状态" :label-width="80">
              <NSelect
                v-model:value="queryItems.is_check"
                style="width: 200px;"
                :options="data.is_check_data"
                clearable
                label-field="name"
                    value-field="id"
                placeholder="选择审核状态"
              />
            </QueryBarItem>



          </template>
        </CrudTable>


      </CommonPage>
      
       <n-drawer v-model:show="data.show_detail" width="760px">
        <n-drawer-content :title="'订单编号'+data.detail.id" closable>
              <n-divider dashed>包含商品</n-divider>
              <n-descriptions  style="width: 100%;" label-placement="left" bordered :column="1" >
                <n-descriptions-item label="商品名称">数量</n-descriptions-item>
                <n-descriptions-item :label="item2.title" v-for="item2 in data.detail.goods_arr">{{item2.num}}</n-descriptions-item>
              </n-descriptions>
              <n-divider dashed>支付详情</n-divider>
              <n-descriptions  style="width: 100%;" label-placement="left" bordered :column="3" >
                <n-descriptions-item label="订单原价">{{ data.detail.original_price??data.detail.price }}</n-descriptions-item>
                <n-descriptions-item label="订单总额">{{ data.detail.price }}</n-descriptions-item>
                <n-descriptions-item label="整单折扣">{{ data.detail.zhekou??'100' }}%</n-descriptions-item>
                <n-descriptions-item label="优惠合计">{{data.detail.deduct_price}}</n-descriptions-item>
                <n-descriptions-item label="实际付款">{{data.detail.pay_money}}</n-descriptions-item>
                <n-descriptions-item label="优惠抵扣">{{data.detail.other.deduct}}</n-descriptions-item>
                <n-descriptions-item label="积分抵扣">{{data.detail.cdp_dk}}</n-descriptions-item>
                <n-descriptions-item label="储值抵扣">{{data.detail.weimei_dk}}</n-descriptions-item>
                <n-descriptions-item label="赠送金抵扣">{{data.detail.free_dk}}</n-descriptions-item>
                <n-descriptions-item label="卡券抵扣">{{data.detail.other.fujia}}</n-descriptions-item>
             </n-descriptions>
              <n-divider dashed>其他信息</n-divider>
              <n-descriptions  style="width: 100%;" label-placement="left" bordered :column="2" >
                <n-descriptions-item label="下单客户">
                  {{data.detail.user_name}}
                </n-descriptions-item>
                <n-descriptions-item label="下单时间">{{data.detail.created_at}}</n-descriptions-item>
                <n-descriptions-item label="订单状态">{{data.detail.status_format}}</n-descriptions-item>
                <n-descriptions-item label="打板">{{data.detail.is_db==1?'是':'否'}}</n-descriptions-item>

                <n-descriptions-item label="录入人员">{{data.detail.butler}}</n-descriptions-item>
                <n-descriptions-item label="健康顾问人员">{{data.detail.face_name}}</n-descriptions-item>
             </n-descriptions>
              <n-divider dashed>收款信息</n-divider>
              <n-descriptions  style="width: 100%;" label-placement="left" bordered :column="1" >
                <n-descriptions-item label="收款账户">收款金额</n-descriptions-item>
                <n-descriptions-item :label="item2.fkfs" v-for="item2 in data.detail.fkfs_arr">{{item2.price}}</n-descriptions-item>
              </n-descriptions>
              <n-divider dashed>支付凭证</n-divider>
              <n-descriptions  style="width: 100%;" label-placement="left" bordered :column="1" >
                <n-descriptions-item label="备注">{{data.detail.remark}}</n-descriptions-item>
                <n-descriptions-item label="凭证">
                  <n-scrollbar x-scrollable>
                  <div style="display: flex">
                        <n-image style="height:100px;border-radius: 5px;margin-right: 2px"  :src="img" v-for="img in data.detail.water"/>
                  </div>
                  </n-scrollbar>
                </n-descriptions-item>
             </n-descriptions>
              <n-divider dashed>退款信息</n-divider>
              <n-descriptions  style="width: 100%;" label-placement="left" bordered :column="2" >
                <n-descriptions-item label="退款金额">{{data.detail.refund_price}}</n-descriptions-item>
                <n-descriptions-item label="退款时间">{{data.detail.refund_time}}</n-descriptions-item>
                <n-descriptions-item label="退款备注">{{data.detail.refund_remark}}</n-descriptions-item>
             </n-descriptions>


        </n-drawer-content>
       </n-drawer>

    </NLayoutContent>
  </NLayout>


  <!-- 业务页面 -->
</template>
